<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="outer">
    <div class="router"><a href="#/one">1</a></div>
    <div class="router"><a href="#/two">2</a></div>
    <div id="main">欢迎</div>
</div>

<script>
/*?
    ? 总结步骤：
    ? 1. 添加hashchange和load的eventListener  执行refresh函数
    ? 2. refresh函数的作用是获取路径(#后的) 然后调用里面的回调函数
    ? 3. 当点击路由时，路径变化触发监听器事件，监听器事件触发refresh函数，refresh函数触发此路径绑定的回调函数，切换显示
?*/
class Router {
    constructor() {
        this.routes = {}
        this.curUrl = ''
    }
    init() {
        window.addEventListener('load', this.refresh.bind(this))
        window.addEventListener('hashchange', this.refresh.bind(this))
    }
    route(path, callback) {
        this.routes[path] = callback || function () {}
    }
    refresh() {
        this.curUrl = location.hash.slice(1) || '/'
        this.routes[this.curUrl]()
    }
}
const R = new Router()
R.init()
R.route('/one',function (){
    document.getElementById('main').innerText = 'one'
})
R.route('/two',function (){
    document.getElementById('main').innerText = 'two'
})
</script>
</body>
</html>
